#pragma once

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

// 任务个数
#define TaskNum 3

typedef void (*task_t)();//函数指针重命名 

void Print()
{
    std::cout << "I am a Print task" << std::endl;
}
void DownLoad()
{
    std::cout << "I am a Download task" << std::endl;
}
void Flush()
{
    std::cout << "I am a Flush task" << std::endl;
}

// 创建任务数组
task_t tasks[TaskNum]; 

// 加载任务
void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^1777);
    tasks[0] = Print;
    tasks[1] = DownLoad;
    tasks[2] = Flush;
}

// 通过数组下标执行某一条任务
void ExecuteTask(int number)
{
    if(number < 0 || number > 2) return;
    tasks[number]();
}

// 通过随机数选择任务编号
int SelectTask()
{
    return rand() % TaskNum;
}

void work()
{
    while (true)
    {
        int command = 0;
        // 从标准输入读数据
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "pid is : " << getpid() << " handler task" << std::endl;
            ExecuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "sub process : " << getpid() << " quit" << std::endl;
            break;
        }
    }
}